package com.zjdiepu.www.manage.api.yw;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.CarinfoEditStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessVoMapper;
import com.zjdiepu.www.ibiz.dz.IDzRegistrationService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessCarService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.ibiz.yw.IYwCarinfoEditService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.dz.dto.DzRegistration;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwCarinfoEdit;
import com.zjdiepu.www.model.yw.ext.YwCarinfoEditExt;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * yw_车辆信息修改Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2018年01月29日 15时59分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "YwCarinfoEditController", produces="application/json;charset=UTF-8")
@Api(tags = {"yw_车辆信息修改"}, produces="application/json;charset=UTF-8")
public class YwCarinfoEditController extends BaseController {
    @Resource
    private IYwCarinfoEditService ywCarinfoEditService;
    @Resource
    private IYwBusinessCarService ywBusinessCarService;
    @Resource
    private IDzRegistrationService dzRegistrationService;
    @Resource
    private IYwBusinessService ywBusinessService;
    @Resource
    private YwBusinessVoMapper ywBusinessVoMapper;
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: refuse  <br/>
     * @Description: 审核不通过 <br/>
     * @param busiId
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "审核车辆信息修改",response = Boolean.class, httpMethod="POST")
    @RequestMapping(value = "refuse", method = RequestMethod.POST)
    public ApiResponse refuse(String busiId){
    	SysUser currentUser = (SysUser)getCurrentUser();
    	if(StringUtils.isBlank(busiId)) {
    		ExceptionHelper.thow(ResultFlagType.MISSING);
    	}
    	boolean saveAudit = ywCarinfoEditService.saveAudit(busiId, false, currentUser);
        return ApiResponse.success(saveAudit);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: refuse  <br/>
     * @Description: 审核通过 <br/>
     * @param busiId
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "审核车辆信息修改",response = Boolean.class, httpMethod="POST")
    @RequestMapping(value = "pass", method = RequestMethod.POST)
    public ApiResponse pass(String busiId){
    	SysUser currentUser = (SysUser)getCurrentUser();
    	if(StringUtils.isBlank(busiId)) {
    		ExceptionHelper.thow(ResultFlagType.MISSING);
    	}
    	boolean saveAudit = ywCarinfoEditService.saveAudit(busiId, true, currentUser);
        return ApiResponse.success(saveAudit);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: getChangedCarInfo  <br/>
     * @Description: 车辆信息修改列表 <br/>
     * @param ywBusinessQueryRequest
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "获取车辆修改信息",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "getChangedCarInfo", method = RequestMethod.POST)
    public ApiResponse getChangedCarInfo(String busiId){
    	getCurrentUser();
    	if(StringUtils.isBlank(busiId)) {
    		ExceptionHelper.thow(ResultFlagType.MISSING);
    	}
    	//修改车辆信息，如果没有修改,展示车辆信息
    	YwCarinfoEditExt ywCarinfoEditExt = new YwCarinfoEditExt();
    	ywCarinfoEditExt.setBaseWhere();
    	ywCarinfoEditExt.setWhereSql(" AND CONVERT(`CARINFO_EDIT_STATUS` , UNSIGNED) <= " + CarinfoEditStatus.DAI_SHE_HE.getCode());
    	ywCarinfoEditExt.setBusiId(busiId);
    	List<YwCarinfoEdit> ywCarinfoEdits = ywCarinfoEditService.selectByExt(ywCarinfoEditExt);
    	
    	YwCarinfoEdit ywCarinfoEdit = null;
    	if(CollectionUtils.isNotEmpty(ywCarinfoEdits)) {
    		ywCarinfoEdit = ywCarinfoEdits.get(0);
    	}
    	
//       车牌信息
		DzRegistration dzRegistration = new DzRegistration();
		dzRegistration.setBusiId(busiId);
		dzRegistration.setDpStatus(DpStatus.NORMAL.getCode());
		dzRegistration = dzRegistrationService.selectRefined(dzRegistration);
    	boolean hasDzRegistration = false;
    	boolean setDzRegistration = false;
    	if(null == ywCarinfoEdit) {
//    		车辆信息
    		ywCarinfoEdit = new YwCarinfoEdit();
    		YwBusinessCar ywBusinessCar = new YwBusinessCar();
    		ywBusinessCar.setBusiId(busiId);
    		ywBusinessCar.setDpStatus(DpStatus.NORMAL.getCode());
    		ywBusinessCar = ywBusinessCarService.selectRefined(ywBusinessCar);
    		if(null == ywBusinessCar) {
    			ExceptionHelper.thow(String.valueOf(ResultFlagType.MISSING.getCode()), "车辆记录缺失");
    		}
    		BeanUtils.copyProperties(ywBusinessCar, ywCarinfoEdit);
    		
    		if(null != dzRegistration) {
    			setDzRegistration = true;
    			hasDzRegistration = true;
    		}
    		ywCarinfoEdit.setId(null);
    	}  else {
    		if(StringUtils.isBlank(ywCarinfoEdit.getDvm()) && StringUtils.isBlank(ywCarinfoEdit.getLicensePlate())
    				 && StringUtils.isBlank(ywCarinfoEdit.getRegistrationNumber()) && StringUtils.isBlank(ywCarinfoEdit.getRegistrationArea()) 
    				&& null == ywCarinfoEdit.getDateRegistrationFirst() && null == ywCarinfoEdit.getDateRegistrationNow()) { //，取出老的车牌信息
    			if(null != dzRegistration) {
    				setDzRegistration = true;
    				hasDzRegistration = true;
    			}
    		} else { //只要有车牌信息，就认为已经修改过了车牌信息，只取保存在记录中的数据
    			hasDzRegistration = true;
    		}
    	}
    	//车牌信息赋值
    	//车牌信息不在此处修改了
    	setDzRegistration = false;
    	if(setDzRegistration) {
			ywCarinfoEdit.setDvm(dzRegistration.getDvm());
			ywCarinfoEdit.setDateRegistrationFirst(dzRegistration.getDateRegistrationFirst());
			ywCarinfoEdit.setDateRegistrationNow(dzRegistration.getDateRegistrationNow());
			ywCarinfoEdit.setLicensePlate(dzRegistration.getLicensePlate());
			ywCarinfoEdit.setRegistrationNumber(dzRegistration.getRegistrationNumber());
			ywCarinfoEdit.setRegistrationArea(dzRegistration.getRegionRegistration());
    	}
    	//车牌信息不在此处修改了
    	hasDzRegistration = false;
    	ywCarinfoEdit.setHasregistration(hasDzRegistration);
		
        return ApiResponse.success(ywCarinfoEdit);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: carinfoChangeList  <br/>
     * @Description: 车辆信息修改列表 <br/>
     * @param ywBusinessQueryRequest
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "车辆信息修改列表",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "carinfoChangeList", method = RequestMethod.POST)
    public ApiResponse carinfoChangeList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser sysUser = (SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.setBaseWhere();
        ywBusinessQueryRequest.setBankLoan(sysUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
//        ywBusinessQueryRequest.setMinBusiStatus(BusiStatus.CHE_INFO_REPLAY_OK.getCode()); // 车辆信息已复审(450)   <= 业务数据状态 <= 银行已放款(500) ,并且 业务主表的抵押时间（pledge_time）= nul；
//        ywBusinessQueryRequest.setMaxBusiStatus(BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode());//银行已放款（包括）；
//        @update 2018-03-19 现在修改为 业务数据状态 = 车辆信息已复审(450)
        ywBusinessQueryRequest.addBusiStatus(BusiStatus.CHE_INFO_REPLAY_OK.getCode());
        ywBusinessQueryRequest.setWhereSql(" AND B.`PLEDGE_TIME` IS NULL");
        ywBusinessQueryRequest.setClxg(true);//车辆修改列表
        ywBusinessQueryRequest.setCarinfoEditStatus(CarinfoEditStatus.DAI_SHE_HE.getCode()); /*<=100(已保存和待审核)*/
        Date applyCarinfoTimeStartDate = ywBusinessQueryRequest.getApplyCarinfoTimeStartDate();
        if(applyCarinfoTimeStartDate != null) {
        	ywBusinessQueryRequest.setApplyCarinfoTimeStart(DateUtil.truncAndAddDays(applyCarinfoTimeStartDate, 0).getTime() / 1000);
        } 
        Date applyCarinfoTimeEndDate = ywBusinessQueryRequest.getApplyCarinfoTimeEndDate();
        if(applyCarinfoTimeEndDate != null){
        	ywBusinessQueryRequest.setApplyCarinfoTimeEnd(DateUtil.truncAndAddDays(applyCarinfoTimeEndDate, 1).getTime() / 1000);
        }
        int records = ywBusinessService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessService.selectMultiByExt(ywBusinessQueryRequest);
            ywBusinessVoMapper.mapper(ywBusinesss);
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: carinfoChangeList  <br/>
     * @Description: 车辆信息修改列表 <br/>
     * @param ywBusinessQueryRequest
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "车辆信息修改历史列表",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "carinfoChangeHisList", method = RequestMethod.POST)
    public ApiResponse carinfoChangeHisList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser sysUser = (SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.setBaseWhere();
        ywBusinessQueryRequest.setBankLoan(sysUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
        ywBusinessQueryRequest.setClxgHis(true);//车辆修改历史列表
        Date applyCarinfoTimeStartDate = ywBusinessQueryRequest.getApplyCarinfoTimeStartDate();
        if(applyCarinfoTimeStartDate != null) {
        	ywBusinessQueryRequest.setApplyCarinfoTimeStart(DateUtil.truncAndAddDays(applyCarinfoTimeStartDate, 0).getTime() / 1000);
        } 
        Date applyCarinfoTimeEndDate = ywBusinessQueryRequest.getApplyCarinfoTimeEndDate();
        if(applyCarinfoTimeEndDate != null){
        	ywBusinessQueryRequest.setApplyCarinfoTimeEnd(DateUtil.truncAndAddDays(applyCarinfoTimeEndDate, 1).getTime() / 1000);
        }
        int records = ywBusinessService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessService.selectMultiByExt(ywBusinessQueryRequest);
            ywBusinessVoMapper.mapper(ywBusinesss);
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增yw_车辆信息修改 <br/>
     * @param ywCarinfoEdit
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增yw_车辆信息修改", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute YwCarinfoEdit ywCarinfoEdit) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywCarinfoEdit.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywCarinfoEdit.setModifierName(currentUser.getName());
        ywCarinfoEditService.saveUpdateAndDelete(ywCarinfoEdit, OperateType.add);
        return ApiResponse.success(ywCarinfoEdit);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除yw_车辆信息修改<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除yw_车辆信息修改", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywCarinfoEditService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用yw_车辆信息修改<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用yw_车辆信息修改", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywCarinfoEditService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用yw_车辆信息修改<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用yw_车辆信息修改", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywCarinfoEditService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改yw_车辆信息修改 <br/>
     * @param ywCarinfoEdit
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改yw_车辆信息修改", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute YwCarinfoEdit ywCarinfoEdit) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywCarinfoEdit.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywCarinfoEdit.setModifierName(currentUser.getName());
    	ywCarinfoEditService.saveUpdateAndDelete(ywCarinfoEdit, OperateType.edit);
        return ApiResponse.success(ywCarinfoEdit);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询yw_车辆信息修改<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询yw_车辆信息修改", response = YwCarinfoEdit.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       YwCarinfoEdit ywCarinfoEdit = ywCarinfoEditService.selectById(id);
       if(null == ywCarinfoEdit) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(ywCarinfoEdit);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询yw_车辆信息修改 <br/>
     * @param ywCarinfoEditExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询yw_车辆信息修改",response = YwCarinfoEdit.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute YwCarinfoEditExt ywCarinfoEditExt){
        ywCarinfoEditExt.notDeleted();
        PageVo page = getPage(ywCarinfoEditExt);
        int records = ywCarinfoEditService.countByExt(ywCarinfoEditExt);
        page.setRecords(records);
        if (records > 0) {
            List<YwCarinfoEdit> ywCarinfoEdits = ywCarinfoEditService.selectByExt(ywCarinfoEditExt);
            page.setRows(ywCarinfoEdits);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

}
